package socket

import (
	"net"
	"strconv"

	"jk/jklog"
)

type SmartEyeArgs struct {
	ip   string
	port int
}

type SmartEye struct {
	args SmartEyeArgs
	conn *net.Conn
}

func NewSmartEye(ip string, port int) *SmartEye {
	return new(SmartEye{
		SmartEyeArgs{
			ip:   ip,
			port: port,
		},
	})
}

func (s *SmartEye) ConnectServer() error {
	str := s.args.ip + ":" + strconv.Itoa(s.args.port)
	s.conn, err = net.Dial("tcp", str)
	if err != nil {
		jklog.L().Errorln("dial ", str, " error :", err)
		return err
	}
	defer s.conn.Close()
}

/** return len of write */
func (s *SmartEye) WriteRequest(value string) int {
	if s.conn == nil {
		jklog.L().Errorln("no connect")
		return 0
	}
	w, err := s.conn.Write(value)
	if err == nil {
		return w
	}
	jklog.L().Errorln("write error : ", err)
	return 0
}

/** read data, read 1024 every time
 *  return read len
 */
func (s *SmartEye) Read(buf []byte) int {
	if s.conn == nil {
		jklog.L().Errorln("no connect")
		return 0
	}
	buf = make([]byte, 1024)
	l, err := s.conn.Read(buf)
	if err == nil {
		return l
	}
	jklog.L().Errorln("read error : ", err)
	return 0
}
